import ZW_DC1000
DC1000 = ZW_DC1000.DC1000()

import pandas as pd
import datetime
import os
import openpyxl
fileName = 'voltage.xlsx'
if not os.path.isfile(fileName):
    dfData = {'time': []}
    for i in range(1,9):
        dfData['通道'+str(i)+'电压/V']=[]
    df = pd.DataFrame(dfData)  # 创建DataFrame
    df.to_excel(fileName, index=False)  # 存表，去除原始索引列（0,1,2...）
workbook = openpyxl.load_workbook(fileName)
sheets_name = workbook.sheetnames  # 获取工作薄的所有的sheet名称
worksheet = workbook[sheets_name[0]]  # 获取工作薄中的第一个sheet


from tkinter import *
from tkinter import messagebox
class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master=master
        self.channelstate = {}
        self.voltage = {}
        self.current = {}
        self.channelchoice={}
        self.ratio={}
        self.detectvoltage = {}

        self.createWidget()
        self.pack()
    def createWidget(self):
        Label(self,text="IP Address").grid(column=0,row=0)
        self.IP_address = StringVar()
        self.IP_address.set("192.168.2.22")
        Entry(self, textvariable=self.IP_address).grid(column=1,row=0)
        Label(self, text="端口号").grid(column=2, row=0)
        self.port = IntVar()
        self.port.set(8080)
        Entry(self, textvariable=self.port).grid(column=3, row=0)
        Button(self,text="连接",command=self.connect).grid(column=4,row=0)
        Label(self, text="设置斜率 mV/s").grid(column=0, row=1)
        self.slope = IntVar()
        Entry(self, textvariable=self.slope).grid(column=1, row=1)
        Button(self, text="设置", command=self.changeslope).grid(column=2, row=1)
        Label(self,text="通道名").grid(column=0, row=3)
        Label(self, text="通道开关状态").grid(column=1, row=3)
        Label(self, text="设置电压:").grid(column=4, row=3)
        Label(self, text="电流:").grid(column=6, row=3)
        Label(self, text="实时监测电压:").grid(column=8, row=3)

        for item in range(1,9):
            Label(self,text="ch"+str(item)).grid(column=0,row=3+item)
            self.channelstate[str(item)] = StringVar()
            self.channelstate[str(item)].set("关")
            Label(self, textvariable=self.channelstate[str(item)]).grid(column=1, row=3 + item)
            Button(self, text="打开", command=lambda arg=item: self.openchannel(arg)).grid(column=2, row=3 + item)
            Button(self, text="关闭", command=lambda arg=item: self.closechannel(arg)).grid(column=3, row=3 + item)
            self.voltage[str(item)] = DoubleVar()
            Entry(self, textvariable=self.voltage[str(item)]).grid(column=4, row=3 + item)
            Button(self, text="电压设置",command=lambda arg=item: self.changevoltage(arg,self.voltage[str(arg)].get())).grid(column=5, row=3 + item)
            self.current[str(item)] = DoubleVar()
            Label(self, textvariable=self.current[str(item)]).grid(column=6, row=3 + item)
            self.current[str(item)].set(0)
            Button(self, text="电流检测", command=lambda arg=item: self.getcurrent(arg)).grid(column=7, row=3 + item)
            self.detectvoltage[str(item)] = DoubleVar()
            Label(self, textvariable=self.detectvoltage[str(item)]).grid(column=8, row=3 + item)
            self.detectvoltage[str(item)].set(0)
            Button(self, text="电压检测", command=lambda arg=item: self.getchannelvoltage(arg)).grid(column=9, row=3 + item)

        for it in range(1,5):
            # print(it)
            Label(self,text="第"+str(it)+"Channel").grid(column=0,row=11+it)
            self.channelchoice[str(it)]=IntVar()
            Entry(self,textvariable=self.channelchoice[str(it)]).grid(column=1,row=11+it)
            Label(self,text="Ratio"+str(it)).grid(column=2,row=11+it)
            self.ratio[str(it)]=IntVar()
            Entry(self,textvariable=self.ratio[str(it)]).grid(column=3,row=11+it)
        Label(self,text="Amplitude").grid(column=4,row=12)
        self.amplitude=DoubleVar()
        Entry(self,textvariable=self.amplitude).grid(column=5,row=12)
        Button(self,text="set",command=self.controlfourchannelvotlage).grid(column=6,row=12)
        Button(self, text="savevoltage", command=self.savevoltag).grid(column=9, row=12)
    def connect(self):
        info=DC1000.ethernet_connect(self.IP_address.get(), self.port.get())
        if info == 0xFF:
            message="设备连接成功"
            #初始化通道开关状态
            for i in range(1,9):
                self.checkchannelstate(i)
        else:
            message="设备连接失败"
        messagebox.showinfo("连接情况",message)
        self.autogetcurent()
        self.autogetvoltage()
    def openchannel(self,channelnumber):
        DC1000.open_ch(channelnumber)
        self.channelstate[str(channelnumber)].set("开")
        # messagebox.showinfo("通道"+str(channelnumber)+"打开情况", info)
    def closechannel(self,channelnumber):
        DC1000.close_ch(channelnumber)
        self.channelstate[str(channelnumber)].set("关")
        # messagebox.showinfo("通道" + str(channelnumber) + "关闭情况", info)
    def checkchannelstate(self,channelnumber):
        print(DC1000._check_status(channelnumber))
        if(DC1000._check_status(channelnumber)):
            self.channelstate[str(channelnumber)].set("开")
        else:
            self.channelstate[str(channelnumber)].set("关")
    def changeslope(self):
        info=DC1000.set_slope(self.slope.get())
        # messagebox.showinfo("斜率设置情况", info)
    def changevoltage(self,channelnumber,voltage):
        info=DC1000.set_vol(channelnumber,voltage)
        # messagebox.showinfo("通道电压改变情况", info)
    def getcurrent(self,channelnumber):
        a=DC1000.get_current(channelnumber)
        a=float('%.4g' % a)
        self.current[str(channelnumber)].set(a)
    def autogetcurent(self):
        for channelnumber in range(1,9):
            self.getcurrent(channelnumber)
        self.after(1000,self.autogetcurent)
    def controlfourchannelvotlage(self):
        for i in range(1,5):
            voltagechange=self.amplitude.get()*self.ratio[str(i)].get()
            # print(self.channelchoice[str(i)].get(), self.voltage[str(self.channelchoice[str(i)].get())].get(),
            #       self.voltage[str(self.channelchoice[str(i)].get())].get() + voltagechange)
            if 0<self.channelchoice[str(i)].get()<9:
                self.getchannelvoltage(self.channelchoice[str(i)].get())
                self.changevoltage(self.channelchoice[str(i)].get(), self.detectvoltage[str(self.channelchoice[str(i)].get())].get()+voltagechange)
    def getchannelvoltage(self,channelnumber):
        b = DC1000.get_vol(channelnumber)
        b = float('%.4g' % b)
        self.detectvoltage[str(channelnumber)].set(b)
    def autogetvoltage(self):
        for channelnumber in range(1,9):
            self.getchannelvoltage(channelnumber)
        self.after(1000,self.autogetvoltage)
    def savevoltag(self):
        timevoltageinfo=[]
        timevoltageinfo.append(datetime.datetime.now())
        for channelnumber in range(1,9):
            timevoltageinfo.append(self.detectvoltage[str(channelnumber)].get())
        worksheet.append(timevoltageinfo)
        workbook.save(fileName)

root=Tk()
root.title("ZW-DC电压检测和设置系统")
root.geometry("1000x1000+100+200")
ZW_DC_GUIapp=Application(master=root)
root.mainloop()



